package com.example.testi18n.inceptor;

import com.example.testi18n.constant.LanguageConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobendan
 * @version v1.0.0
 * @className LocaleInterceptor
 * @package com.slodon.bbc.core.aop
 * @description 国际化语言拦截器
 * @date 2022-09-26 11:02
 */
public class LocaleInterceptor extends LocaleChangeInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LocaleInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
        String language = request.getHeader("language");
        log.info("=================>>>>请求的语言类型:{}", language);

        if (language == null || ObjectUtils.isEmpty(language) || "null".equalsIgnoreCase(language)) {
            language = LanguageConstant.ENGLISH;
        }

        if (LanguageConstant.ENGLISH.equalsIgnoreCase(language)) {
            language = LanguageConstant.ENGLISH;
        }

        if (LanguageConstant.CHINESE.equalsIgnoreCase(language)) {
            language = LanguageConstant.CHINESE;
        }
        if (checkHttpMethod(request.getMethod())) {
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            if (localeResolver == null) {
                throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
            }
            try {
                localeResolver.setLocale(request, response, parseLocaleValue(language));
            } catch (IllegalArgumentException ex) {
                if (isIgnoreInvalidLocale()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Ignoring invalid locale value [" + language + "]: " + ex.getMessage());
                    }
                } else {
                    throw ex;
                }
            }
        }
        return true;
    }

    private boolean checkHttpMethod(String currentMethod) {
        String[] configuredMethods = getHttpMethods();
        if (ObjectUtils.isEmpty(configuredMethods)) {
            return true;
        }
        for (String configuredMethod : configuredMethods) {
            if (configuredMethod.equalsIgnoreCase(currentMethod)) {
                return true;
            }
        }
        return false;
    }
}
